package cn.com.huzo.webapp.controller;

import huzofw.common.Constants;
import java.util.Collection;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 在线会话管理
 *
 * @author 吴旭
 */
@RequiresPermissions("session:*")
@Controller
@RequestMapping("/sessions")
public class SessionController {

    @Autowired
    private SessionDAO sessionDAO;

    /**
     * 显示在线用户
     *
     * @return
     */
    @RequestMapping()
    public ModelAndView list() {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        //model.addAttribute("sessions", sessions);
        //model.addAttribute("sessionCount", sessions.size());        
        ModelAndView view = new ModelAndView();
        view.addObject("sessions", sessions);
        view.addObject("sessionCount", sessions.size());
        view.setViewName("admin.online_user.list.def");
        return view;
    }

    @RequestMapping("/{sessionId}/forceLogout")
    public String forceLogout(
            @PathVariable("sessionId") String sessionId, RedirectAttributes redirectAttributes) {
        try {
            Session session = sessionDAO.readSession(sessionId);
            if (session != null) {
                session.setAttribute(Constants.SESSION_FORCE_LOGOUT_KEY, Boolean.TRUE);
            }
        } catch (Exception e) {/*ignore*/
        }
        redirectAttributes.addFlashAttribute("msg", "强制退出成功！");
        return "redirect:/sessions.html";
    }
}
